<!-- 地图拾取经纬度 -->
<template>
  <div class="map-address">
    <div id="mapDiv"></div>
    <div class="left-top">
      <el-select
        v-model="input"
        remote
        :remote-method="searchWithName"
        filterable
        no-data-text="暂无数据"
        placeholder="请输入关键词搜索"
        class="address-search"
      >
        <el-option
          v-for="(item, index) in addressList"
          :key="index"
          :label="item.name"
          :value="index"
          @click.native="selectOneAddr(item.address + item.name)"
        >
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  props: {
    dialogForm: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      lng: 0,
      lat: 0,
      address: "",
      marker: {},
      input: "",
      map: {},
      addressList: [],
    };
  },
  computed: {},
  watch: {
    input(val) {
      if (!val) {
        this.addressList = [];
        // 用来清空删除太快时候出现列表的bug
        setTimeout(() => {
          this.addressList = [];
        }, 3000);
      }
    },
    dialogForm: {
      handler(val) {
        this.$nextTick(() => {
          this.map.clearOverLays();
          if (val.lat) {
            let label = new T.Label({
              text: val.address,
              position: { lat: val.lat.toFixed(5), lng: val.lng.toFixed(5) },
              offset: new T.Point(10, -20),
            });
            this.map.addOverLay(label);
            let marker = new T.Marker({ lng: val.lng, lat: val.lat });
            this.map.addOverLay(marker);
            this.map.panTo({ lng: val.lng, lat: val.lat }, 16);
          } else {
            this.map.centerAndZoom(new T.LngLat(116.401003, 39.903117), 12);
          }
        });
      },
      deep: true, //对象内部的属性监听，也叫深度监听
      immediate: true,
    },
  },
  methods: {
    confirm() {
      if (this.lng && this.lat && this.address) {
        // this.$emit("closeMapaddressDialog", false);
      } else {
        this.$message.warning("鼠标点选或搜索选中地址后再进行确认");
      }
    },
    // 搜索 天地图LocalSearch
    searchWithName(val) {
      if (val) {
        let that = this;
        var config = {
          pageCapacity: 10, //每页显示的数量
          onSearchComplete: localSearchResult, //接收数据的回调函数
        };
        //创建搜索对象
        let localsearch = new T.LocalSearch(that.map, config);
        localsearch.search(val);
        function localSearchResult(result) {
          //清空地图及搜索列表
          clearAll();
          //解析建议词信息
          suggests(result.pois);
        }
        //解析建议词信息
        function suggests(obj) {
          if (obj && obj.length) {
            //建议词提示，如果搜索类型为公交规划建议词或公交站搜索时，返回结果为公交信息的建议词。
            that.addressList = obj;
          }
        }
        //清空地图及搜索列表
        function clearAll() {
          that.map.clearOverLays();
        }
      } else {
        this.addressList = [];
      }
    },
    // 初始化地图
    initMap() {
      var map;
      var zoom = 12;
      map = new T.Map("mapDiv", {
        projection: "EPSG:4326",
      });
      map.centerAndZoom(new T.LngLat(116.401003, 39.903117), zoom);
      //创建缩放平移控件对象
      let control = new T.Control.Zoom();
      //添加缩放平移控件
      map.addControl(control);
      this.map = map;
      //创建对象
      let geocode = new T.Geocoder();
      // 鼠标点击逆地理搜索
      map.addEventListener("click", function (e) {
        geocode.getLocation(e.lnglat, searchResult);
      });
      let that = this;
      function searchResult(result) {
        if (result.getStatus() == 0) {
          that.address = result.getAddress();
          that.$emit("click", {
            lnglat: { lng: result.location.lon, lat: result.location.lat },
            address: that.address,
          });
          let label = new T.Label({
            text: that.address,
            position: that.marker.getLngLat(),
            offset: new T.Point(10, -20),
          });
          map.addOverLay(label);
        } else {
          map.clearOverLays();
        }
      }
      var cp = new T.CoordinatePickup(map, { callback: getLngLat });
      cp.addEvent();
      function getLngLat(lnglat) {
        map.clearOverLays();
        that.lng = lnglat.lng.toFixed(6);
        that.lat = lnglat.lat.toFixed(6);
        that.marker = new T.Marker(new T.LngLat(that.lng, that.lat)); // 创建点
        map.addOverLay(that.marker);
      }
    },
    selectOneAddr(val) {
      let that = this;
      that.map.clearOverLays();
      //创建对象
      let geocoder = new T.Geocoder();
      geocoder.getPoint(val, searchResult);
      function searchResult(result) {
        if (result.getStatus() == 0) {
          that.map.panTo(result.getLocationPoint(), 16);
          //创建标注对象
          var marker = new T.Marker(result.getLocationPoint());
          //向地图上添加标注
          let label = new T.Label({
            text: val,
            position: result.getLocationPoint(),
            offset: new T.Point(10, -20),
          });
          that.map.addOverLay(label);
          that.map.addOverLay(marker);
          that.address = val;
          that.lng = result.getLocationPoint().lng;
          that.lat = result.getLocationPoint().lat;
          that.$emit("click", {
            lnglat: { lng: that.lng, lat: that.lat },
            address: that.address,
          });
        } else {
          this.$message.warning("定位出错请重新选择");
        }
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initMap();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
};
</script>
<style lang="scss" scoped>
.cur {
  cursor: pointer;
}

.map-address {
  height: 60vh;
}

#mapDiv {
  height: 100%;
  position: relative;
}

.left-top {
  position: absolute;
  left: 60px;
  top: 10px;
  display: flex;
  flex-direction: column;
}

.address-search {
  width: 12vw;
  z-index: 10000;
}

.address-list {
  display: flex;
  flex-direction: column;
  z-index: 10000;
  background-color: #fff;
  padding: 10px;
  min-width: 18vw;
  border: 1px solid #dcdfe6;

  > div {
    display: flex;
    align-items: center;
    height: 30px;
    cursor: pointer;
    color: #409eff;

    &:hover {
      background-color: #eee;
    }
  }
}
</style>
<style>
.address-search .el-input-group__append,
.el-input-group__prepend {
  background-color: #409eff;
  color: #fff;
}
</style>
